package com.skyworth.tvos.checker;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class CheckerManager implements Runnable {
    static abstract public class CheckerTask {
        private int interval = 1;
        private int currentTick = 0;
        private boolean enabled = true;
        private String taskname = null;

        /**
         * check interval presented in second
         *
         * @param checkInterval
         */
        public CheckerTask(int checkInterval, String name) {
            interval = checkInterval;
            this.taskname = name;
        }

        public void setInterval(int checkInterval) {
            interval = checkInterval;
        }

        public void disable() {
            currentTick = 0;
            enabled = false;
        }

        public void enable() {
            enabled = true;
        }

        protected final void tick() {
            if (!enabled) {
                return;
            }
            ++currentTick;
            if (currentTick >= interval) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        taskRun();
                    }
                }).start();
                currentTick = 0;
            }
        }

        public abstract void taskRun();
    }

    private List<CheckerTask> checkTasks;
    private ScheduledThreadPoolExecutor timer = null;
    private static CheckerManager theChecker = null;

    private CheckerManager() {
        checkTasks = new ArrayList<CheckerTask>();
    }

    public static CheckerManager getChecker() {
        if (theChecker == null) {
            theChecker = new CheckerManager();
        }
        return theChecker;
    }

    public void start() {
        timer = new ScheduledThreadPoolExecutor(1);
        timer.scheduleAtFixedRate(this, 0, 1000, TimeUnit.MILLISECONDS);
    }

    public void stop() {
        timer.shutdown();
        timer = null;
    }

    public synchronized void addTask(CheckerTask task) {
        checkTasks.add(task);
    }

    public synchronized boolean removeTask(CheckerTask task) {
        if (checkTasks == null)
            return false;

        synchronized (checkTasks) {
            return checkTasks.remove(task);
        }
    }

    @Override
    public synchronized void run() {
        synchronized (checkTasks) {
            for (CheckerTask task : checkTasks) {
                task.tick();
            }
        }
    }
}
